package edu.nf.supermarket.service.impl;

import edu.nf.supermarket.entity.Coupon;
import edu.nf.supermarket.entity.UserCoupon;
import edu.nf.supermarket.mapper.CouponMapper;
import edu.nf.supermarket.mapper.UserCouponMapper;
import edu.nf.supermarket.service.UserCouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @author gwf
 * @date 2025-06-17
 */
@Service("userCoupon")
public class UserCouponServiceImpl implements UserCouponService {
    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private UserCouponMapper userCouponMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void issueNewUserCoupon(Integer userId) {
        // 获取新用户优惠券
        Coupon newUserCoupon = couponMapper.findNewUserCouponByName("新用户优惠券");
        if (newUserCoupon == null){
            System.out.println("没有找到新人优惠卷");
            throw new RuntimeException("新人优惠卷模版未配置!");
        }

        // 检查用户是否已经领取过新人优惠券
        int count = userCouponMapper.countUserCouponByUserIdAndCouponId(userId, newUserCoupon.getCouponId());
        if (count > 0){
            System.out.println("用["+ userId + "]已经领取过新人优惠卷，无需重复发放");
            return;
        }

        // 生成有效日期
        LocalDateTime start = LocalDateTime.now();
        LocalDateTime end = start.plusDays(7);

        // 创建用户优惠券记录
        UserCoupon userCoupon = new UserCoupon();
        userCoupon.setUserId(userId);
        userCoupon.setCouponId(newUserCoupon.getCouponId());
        userCoupon.setCouponStatus((byte) 0);
        userCoupon.setStartTime(start);
        userCoupon.setEndTime(end);

        userCouponMapper.insertUserCoupon(userCoupon);
        System.out.println("成功为用户["+ userId + "]发放新人优惠卷:" + newUserCoupon.getCouponName());
    }
}
